package com.xr.util;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Arnold Yand
 * @summary web请求相关处理工具类
 */
public class ServletUtil {
  /**
   * 获取request中参数集合，如果有多个值的，获取的是数组
   * @param request
   * @return
   */
  public static Map<String, Object> getAllRequestParameter(HttpServletRequest request) {
    Map<String, Object> parameterMap = new HashMap<String, Object>();
    Map<String, String[]> paramMap = request.getParameterMap();
    Object finalValue = null;
    for (String key : paramMap.keySet()) {
      String[] value = paramMap.get(key);
      if (value != null) {
        switch (value.length) {
          case 0: {
            finalValue = null;
            break;
          }
          case 1: {
            finalValue = value[0].trim();
            break;
          }
          default: {
            for (int i = 0; i < value.length; i++) {
              if (value[i] != null) {
                value[i] = value[i].trim();
              }
            }
            finalValue = value;
          }
        }
      }
      parameterMap.put(key, finalValue);
    }

    return parameterMap;
  }
}
